<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<script setup lang="ts">
  import { DocumentEditor } from '@onlyoffice/document-editor-vue'
  import { computed } from 'vue'

  const props = defineProps<{
    file: string
    id: string
    mode: 'view' | 'edit'
    userName?: string
  }>()

  // 本地 Document Server 地址
  const documentServerUrl = import.meta.env.VITE_DOC_URL ?? ''

  // 计算配置
  const config = computed(() => ({
    document: {
      fileType: getFileType(props.file),
      key: generateKey(props.id),
      title: getFileName(props.file),
      url: props.file,
    },
    documentType: 'word',
    editorConfig: {
      mode: props.mode, // 预览模式
      lang: 'zh-CN',
      user: {
        name: props.userName ?? 'admin',
      },
    },
    customization: {
      hideRightMenu: false,
    },
  }))

  // 获取文件类型
  const getFileType = (filePath: string) => {
    const ext = filePath.split('.').pop()?.toLowerCase()
    switch (ext) {
      case 'docx':
        return 'docx'
      case 'doc':
        return 'doc'
      case 'pdf':
        return 'pdf'
      case 'xlsx':
        return 'xlsx'
      case 'pptx':
        return 'pptx'
      default:
        return 'docx'
    }
  }

  // 生成唯一 key
  const generateKey = (filePath: string) => {
    return btoa(filePath).replace(/[^a-zA-Z0-9]/g, '')
  }

  // 获取文件名
  const getFileName = (filePath: string) => {
    return filePath.split('/').pop() ?? 'document'
  }

  const onDocumentReady = (document: any) => {
    console.log('文档加载完成', document)
  }

  const onLoadComponentError = (error: any) => {
    console.error('加载组件错误', error)
  }

  const onRequestSaveAs = (event: any) => {
    console.log('请求保存', event)
  }

  const onRequestEditRights = (event: any) => {
    console.log('请求编辑权限', event)
  }
</script>

<template>
  <div class="h-full w-full">
    <DocumentEditor
      :id="props.id"
      :documentServerUrl="documentServerUrl"
      :config="config"
      :events_onDocumentReady="onDocumentReady"
      :onLoadComponentError="onLoadComponentError"
      :events_onRequestSaveAs="onRequestSaveAs"
      :events_onRequestEditRights="onRequestEditRights"
    />
  </div>
</template>

<style scoped>
  /* 确保编辑器占满容器 */
  :deep(.onlyoffice-editor) {
    height: 100% !important;
    width: 100% !important;
  }
</style>
